package cn.zd.demo1.broadcast;

import static cn.zd.demo1.broadcast.MyBroadCastConstant.ACTION_ALARM;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Vibrator;
import android.widget.Toast;

public class MyAlarmReceiver extends BroadcastReceiver {
    private Context context;

    public MyAlarmReceiver(Context context) {
        super();
        this.context = context;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent != null && ACTION_ALARM.equals(intent.getAction())) {
            // 获取震动管理器
            Vibrator service = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
            // 震动
            service.vibrate(200);
            Toast.makeText(context,"接收到闹钟广播",Toast.LENGTH_SHORT).show();
            // 因为4.4以后系统方法setRepeating()不发保证按时发送，这里手动重新调起以保证循环
            sendAlarm();
        }
    }
    public void sendAlarm(){
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent in = new Intent(ACTION_ALARM);
        // 创建一个用于广播的延迟意图
        // 针对S+（12）或更高版本，需要在创建PendingIntent时指定FLAG_IMMUTABLE（强烈建议，不可变） 或者 FLAG_MUTABLE（可变）

        PendingIntent pendingintent = PendingIntent.getBroadcast(context,0,in,PendingIntent.FLAG_IMMUTABLE);
        // 设置一次性闹钟，延迟若干秒侯，携带延迟intent发送闹钟广播，但是6.0以后，set()不保证暗屏下会发送 ，必须调用setAndAllowWhileIdle方法
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,1000,pendingintent);
        }else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, 3000, pendingintent);
        }
        // 设置重复闹钟 4.4 以后不保证按时发送
        // alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),100,pendingintent);
    }
}
